<?php
namespace app\admin\validate;
use app\admin\model\Admin;
use think\Db;
use think\facade\Cache;
use think\Validate;
use function mooshroom\pr;

class LoginForm extends Validate{
    protected $rule = [

        'username|用户名'  =>  'require|min:5|max:25',
        'password|密码' =>  'require|min:6|max:128',
        'verity_code|验证码'=>'require|captcha',
    ];
    protected $message  =   [
        'username.require' => '用户名必须!',
        'username.max'     => '名称最多不能超过25个字符',
        'password.number'   => '密码必须',
        'password.regex' => '密码格式错误！'
    ];
    public function Login($data){
        $ip = get_client_ip();
        $at_ip_time = cache('admin_ip_'.$ip);
        $at_time =cache('admin_'.$data['username']);
        if($at_ip_time>config('public.error_time')){
            return ['code'=>20003,'msg'=>'登录频繁，帐号锁定，请联系管理员!'];
        }
        if($at_time>config('public.error_time')){
            return ['code'=>20003,'msg'=>'登录频繁，帐号锁定，请联系管理员!'];
        }
        $model = new Admin();
        $info = $model::findInfoInfoByName($data['username']);
        if(!$info){
           Cache::set('admin_ip_'.$ip,$at_ip_time+1,config('public.login_error'));
           Cache::set('admin_'.$data['username'],$at_ip_time+1,config('public.login_error'));
           return ['code'=>20002,'msg'=>'账号密码错误！'];
       }

       if(!checkPass(trim($data['password']),trim($info->password))) {
           Cache::set('admin_ip_'.$ip,$at_ip_time+1,config('public.login_error'));
           Cache::set('admin_'.$data['username'],$at_ip_time+1,config('public.login_error'));
            return ['code'=>20002,'msg'=>'账号密码错误'];
       }
       if($info->lock == 1){
           return ['code'=>20003,'msg'=>'账号被锁定，请联系管理员!'];
       }
       cache('admin_'.$data['username'],0);
       cache('admin_ip_'.$ip,0);
       $session_id =sha1($info->id);
       session('HTTP_USER_AGENT'.ADMINTYPE,md5($_SERVER['HTTP_USER_AGENT']));
       if(isset($info['password'])) unset($info['password']);
       session('admin'.ADMINTYPE,array_merge($info->toArray(),['token'=>$session_id]));
       if($info->is_supper != 1){
           $menu = Admin::getMenuListByRole($info->role_id);
           cache('menu'.ADMINTYPE,$session_id,$menu);
       }
       (new Admin())->setAdminByid($info->id,'login_time',date('Y-m-d H:i:s'));
        $PrevUrl = session('PrevUrl'.ADMINTYPE);

       return ['code'=>0,'msg'=>'登录成功','url'=>url(isset($PrevUrl)?$PrevUrl:'')];
    }

}